package com.yc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.entity.User;
import com.yc.mapper.UserMapper;
import com.yc.service.IUserService;
import com.yc.service.SendMailService;
import com.yc.util.ValidateCodeUtils;
import com.yc.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * InnoDB free: 4096 kB 前端控制器
 * </p>
 *
 * @author ly
 * @since 2022-05-25
 */
@Controller
@RequestMapping( "//user" )
@Slf4j
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private SendMailService sendMailService;

    @Autowired
    HttpSession session;

    @Resource
    JavaMailSenderImpl javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @RequestMapping( "login" )
    @ResponseBody
    public Result login(String name, String password) {
        Result result = new Result();
        List<User> userList=userService.login(name, password);
        if ( userList == null||userList.size()==0 ) {
            result.setCode(0);
            result.setMsg("账号或密码错误，请确认后重试");
        } else if ( userList.size() == 1 ) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getUcount,name);
            User user = userService.getOne(queryWrapper);
            Integer loginednum = user.getLoginednum();
            if (loginednum == null){
                loginednum = 1;
            }else{
                loginednum += 1;
            }
            userMapper.updateloginednum(loginednum,name);
            String time = ValidateCodeUtils.getDateTime();
            if(user.getCurlogindate() == null && user.getLastlogineddate() == null){
                userMapper.updatelastlogineddate(time,time,name);
            }else{
                String lastlogineddate = user.getCurlogindate();
                userMapper.updatelastlogineddate(lastlogineddate,time,name);
            }
            result.setCode(1);
            result.setMsg("登陆成功");
            result.setData(name);
        }
        return result;
    }


    @RequestMapping( "queryAll" )
    @ResponseBody
    public List< User > queryAll() {
        return userMapper.queryAll();
    }

    @RequestMapping( "queryByUcount" )
    @ResponseBody
    public List< User > queryByUcount(String ucount) {
        return userService.queryByUcount(ucount);
    }

    @RequestMapping( "queryByUid" )
    @ResponseBody
    public List< User > queryByUid(Integer uid) {
        User user=userService.queryByUid(uid);
        List<User> userList=new ArrayList<>();
        userList.add(user);
        return userList;
    }

    @RequestMapping( "freeze" )
    @ResponseBody
    public Integer freeze(@RequestParam( value = "uid" ) Integer uid, @RequestParam( value = "isfreeze" ) Boolean isfreeze) {
        if ( isfreeze ) {
            return userMapper.freeze(uid, "冻结");
        } else {
            return userMapper.freeze(uid, "正常");
        }
    }

    /**
     * 邮箱发送验证码
     * @param user
     * @return
     */
    @PostMapping("/sendmail")
    @ResponseBody
    public Result sendmail(@RequestBody User user) {
        Result result = new Result();
        String email = user.getEmail();
        sendMailService.sendMail(from,javaMailSender,email);
        result.setCode(1);
        result.setMsg("验证码发送成功");
        return result;
    }

    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody Map map){
        //获取前端传过来的验证码
        String code = map.get("mailcode").toString();
        //获取前端传过来的邮箱
        String email = map.get("email").toString();
        sendMailService.addUser(code);
        Result result = new Result();
        if(sendMailService.addUser(code).getCode() == 1){
            //判断当email对应的用户是否为新用户，如果是新用户就自动完成登录
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                //获取注册账号
                String ucount = map.get("ucount").toString();
                String password = map.get("password").toString();
                user = new User();
                user.setUcount(ucount);
                user.setPassword(password);
                user.setEmail(email);
                userService.save(user);
                result.setCode(1);
                result.setMsg("注册成功");
            }else{
                result.setCode(0);
                result.setMsg("用户已注册");
            }
        }else {
            result.setCode(0);
            result.setMsg("验证码验证失败");
        }
        return result;
    }

    @PostMapping("/selectuser")
    @ResponseBody
    public Result selectuser(String ucount){
        Result result=new Result();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUcount,ucount);
        User user = userService.getOne(queryWrapper);
        log.info("user:{}",user);
        result.setCode(1);
        result.setMsg("查询成功");
        result.setData(user);
        return result;
    }

    @PutMapping("/modify")
    @ResponseBody
    public Result modify(@RequestBody User user){
        log.info("user:{}",user);
        Result result = new Result();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUid,user.getUid());
        User user1 = userService.getOne(queryWrapper);
        String mail = user1.getEmail();
        if (user.getEmail().equals(mail)){
            userService.update(user,queryWrapper);
            result.setCode(1);
            result.setMsg("修改成功");
        }else{
            result.setCode(0);
            result.setMsg("修改失败");
        }
        return result;
    }

    /**
     * 比对验证码，验证码比对成功，进行解、绑操作
     * @param ucount
     * @param email
     * @param mailcode
     * @return
     */
    @PutMapping("/removemail")
    @ResponseBody
    public Result removemail(String ucount,String email,String mailcode){
        Result result = new Result();
        System.out.println(mailcode+"_____--------");
        sendMailService.addUser(mailcode);
        if(sendMailService.addUser(mailcode).getCode() == 1){
            if (ucount!=null){
                userMapper.removemail(email,ucount);
//            if(email!=""){
                if (email.equals("")){
                    result.setCode(1);
                    result.setMsg("解绑成功");
                }else{
                    result.setCode(1);
                    result.setMsg("绑定成功");
                }
            }else{
                result.setCode(0);
                result.setMsg("请求出错，请联系管理员");
            }
        }else{
            result.setCode(0);
            result.setMsg("验证码错误，请重新输入");
        }
        return result;
    }

    /**
     * 通过邮箱和密保找回密码
     * @param map
     * @return
     */
    @PutMapping("/findpass")
    @ResponseBody
    public Result findpass(@RequestBody Map map){
        Result result = new Result();
        String ucount = map.get("ucount").toString();
        String email = map.get("email").toString();
        String question = map.get("question").toString();
        String answer = map.get("answer").toString();
        String password = map.get("password2").toString();
        String code = map.get("code").toString();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUcount,ucount);
        User user = userService.getOne(queryWrapper);
        if(question.equals("")){
            if (user.getEmail().equals(email) && code.equals("")){
                sendMailService.sendMail(from,javaMailSender,email);
                result.setCode(1);
                result.setMsg("验证码发送成功");
            }else if (!email.equals("") && !code.equals("")){
                if(sendMailService.addUser(code).getCode() == 1){
                    userMapper.modifypass(password,ucount);
                    result.setCode(1);
                    result.setMsg("找回密码成功");
                }else{
                    result.setCode(0);
                    result.setMsg("验证码不正确");
                }
            }else{
                result.setCode(0);
                result.setMsg("邮箱与当前账号绑定邮箱不一致");
            }
        }else{
            if (user.getQuestion().equals(question) && user.getAnswer().equals(answer)){
                userMapper.modifypass(password,ucount);
                result.setCode(1);
                result.setMsg("找回密码成功");
            }else{
                result.setCode(0);
                result.setMsg("密保错误");
            }
        }
        return result;
    }
}

